<?php

/**
 * default actions.
 *
 * @package    keygenius
 * @subpackage default
 * @author     Dain Nilsson
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class defaultActions extends sfActions {
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request) {
    if($request->hasParameter(KeyGenius::TOKEN))
      $this->forward('server', 'index');
  }

  public function executeShowList(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    $this->forward404Unless($this->getUser()->hasFlash('passwords'));
  }

  public function executeStore(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    $this->processForm($request, new StorePasswordForm());
  }

  public function executeList(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    $this->processForm($request, new ListPasswordsForm());
  }

  public function executeRevoke(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    $this->processForm($request, new RevokeKeyForm());
  }

  public function executeGenerateRevoke(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    $this->processForm($request, new GenerateRevocationForm());
  }

  public function executeDelete(sfWebRequest $request) {
    if(!$request->isSecure()) $this->redirect(str_replace('http://', 'https://', $request->getUri()));
    if($request->hasParameter('id'))
      $this->processForm($request, new DeletePasswordForm(array('id' => $request->getParameter('id'))));
    else
      $this->processForm($request, new DeletePasswordForm());
  }

  private function processForm(sfWebRequest $request, AbstractForm $form) {
    if($request->isMethod('post')) {
      $form->bind($request->getParameter($form->getName()));
      if($form->isValid()) {
        $data = $form->process();
	if(gettype($data) == 'array') {
	  $this->getUser()->setFlash('passwords', $data);
	  $this->redirect('default/showList');
	} else {
          $this->getUser()->setFlash('message', $data);
	  $this->redirect('default/index');
	}
      }
    }
    $this->form = $form;
    $this->action = $this->getContext()->getModuleName().'/'.$this->getContext()->getActionName();
  }

}
